package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单超时处理，每个一分钟检查一次
     */
    @Scheduled(cron = "0 * * * * ? " )
    public void processTimeOutOrder(){
        log.info("订单超时处理:{}", LocalDateTime.now());

        // 根据需求把所有订单查出来
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        // order_time < 当前时间 - 15
        List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单未支付，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }


    /**
     * 订单自动完成，每天凌晨1点处理
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliverOrder(){
        log.info("订单自动完成:{}",LocalDateTime.now());

        // 根据需求把所有订单查出来
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        // order_time < 当前时间 - 60
        List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);

        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }


    }
}















